package com.store.util;

import java.util.List;

/**
 * 分页工具类
 */
public class PageHelper<T>{

    /** 总记录条数 */
    private Integer total;

    /** 每页记录条数 */
    private Integer size;

    /** 当前页数 */
    private Integer current;

    /** 总数据 */
    private List<T> records;


    public PageHelper(Integer size , Integer current ){

        if(size <= 0 || current <= 0 ){
            System.out.println("数据非法！");
            return;
        }

        this.size = size;
        this.current = current;
    }


    /**
     * 获取分页信息
     * @return
     */
    public PageInfo<T> getPageInfo(List<T> records){

        if(size <= 0 || current <= 0 ){
            System.out.println("数据非法！");
            return null;
        }

        this.total = records.size();
        this.records = records;

        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageNum(current);
        pageInfo.setPageSize(size);
        pageInfo.setTotal(total);
        pageInfo.setPages(total/size+(total%size==0?0:1));

        //是否最后一页，第一页，有无前后页
        if(current == total/size+(total%size==0?0:1)){
            pageInfo.setLastPage(true);
            if(total/size+(total%size==0?0:1) == 1){
                pageInfo.setFirstPage(true);
            }else {
                pageInfo.setHasPreviousPage(true);
            }
        }else if(current < total/size+(total%size==0?0:1)){
            pageInfo.setHasNextPage(true);
            if(current == 1){
                pageInfo.setFirstPage(true);
            }else {
                pageInfo.setHasPreviousPage(true);
            }
        }else {
            System.out.println("下标越界");
            return null;
        }

        //分页子集合
        if(total/size+(total%size==0?0:1) == 1){
            pageInfo.setSize(total);
            pageInfo.setList(records);
        }else {
            if(current != (total/size+(total%size==0?0:1))){
                pageInfo.setSize(size);
                pageInfo.setList(records.subList((current-1)*size,(current-1)*size+size));
            }else {
                int num = records.size()-((current-1)*size);
                pageInfo.setSize(num);
                pageInfo.setList(records.subList((current-1)*size,(current-1)*size+num));
            }
        }

        return pageInfo;
    }
}
